package com.vcredit.creditcat.web.app;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.vcredit.creditcat.api.ICustAbilityManager;
import com.vcredit.creditcat.api.ICustProductManager;
import com.vcredit.creditcat.api.ICustRecommendCardManager;
import com.vcredit.creditcat.api.IMyIncomeManager;
import com.vcredit.creditcat.api.IMyWalletManager;
import com.vcredit.creditcat.dto.ability.AbilityDto;
import com.vcredit.creditcat.dto.ability.CreditDimensionDto;
import com.vcredit.creditcat.dto.creditrepository.AuthItemDto;
import com.vcredit.creditcat.dto.product.MerchantProductDto;
import com.vcredit.creditcat.enumtype.AbilityEnum;
import com.vcredit.creditcat.enumtype.AbilityLoanCardCountEnum;
import com.vcredit.creditcat.enumtype.TaskItemEnum;
import com.vcredit.creditcat.model.Cust;
import com.vcredit.creditcat.model.CustAbility;
import com.vcredit.creditcat.util.AppUtil;
import com.vcredit.creditcat.util.Utility;
import com.vcredit.creditcat.vo.AbilityResponseVo;
import com.vcredit.creditcat.vo.AddAbilityParam;
import com.vcredit.creditcat.vo.BindBankCardParamVo;
import com.vcredit.creditcat.vo.CardGrade;
import com.vcredit.creditcat.vo.CardValue;
import com.vcredit.creditcat.vo.CustAbilityDimensionVo;
import com.vcredit.creditcat.vo.CustAbilityVo;
import com.vcredit.creditcat.vo.IndexResponseVo;
import com.vcredit.creditcat.vo.JsonResult;
import com.vcredit.creditcat.vo.NewIndexResonseVo;
import com.vcredit.creditcat.vo.OrderStatistics;
import com.vcredit.creditcat.vo.SimpleAuthItemVo;
import com.vcredit.creditcat.vo.TaskItemResponeseVo;
import com.vcredit.creditcat.vo.TaskItemVO;
import com.vcredit.creditcat.vo.WalletInfo;
import com.vcredit.framework.annotation.Log;


/**
 * 信用账户
 *
 */
@RestController
public class CustAbilityController extends BaseCreditCatController {

	@Reference(version = "1.0")
	private ICustAbilityManager custAbilityManager;

	@Reference(version = "1.0")
	private ICustProductManager custProductManager;

	@Reference(version = "1.0")
	private ICustRecommendCardManager custRecommendCardManager;
	
	@Reference(version = "1.0")
	private IMyWalletManager myWalletManager;
	
	@Reference(version = "1.0")
	private IMyIncomeManager myIncomeManager;


	private Logger logger = LoggerFactory.getLogger(CustAbilityController.class);

	/***
	 * 信用账户
	 * 
	 * @param request
	 * @return
	 * @throws ParseException
	 */
	@Log
	@RequestMapping("/index")
	public IndexResponseVo index(HttpServletRequest request) throws Exception {
		try {

			Cust cust = super.getCust(request);

			// 获取所有特权以及对应的认证项
			List<AbilityDto> allAbilities = custAbilityManager.findAllAbilities();

			// 获取拥有的特权
			List<AbilityDto> listCustAbility = custAbilityManager.findCustOwnAbilities(cust);

			IndexResponseVo responseVo = new IndexResponseVo();
			List<CustAbilityVo> custAbilityVos = new ArrayList<CustAbilityVo>();

			// 当前等级最高的特权
			AbilityDto maxAbilityDto = new AbilityDto();

			for (AbilityDto abilityDto : allAbilities) {

				CustAbilityVo custAbilityVo = new CustAbilityVo();
				custAbilityVo.setValueDesc("1、每贷款成功一次即享信用猫特有返现"+abilityDto.getAbilityRights()+";\r\n"+"2、每办卡成功一次即享信用猫特有返现"+abilityDto.getAbilityRights()+"。");
				custAbilityVo.setPrivilegeId(abilityDto.getAbilityId().toString());
				for (AbilityDto custAbility : listCustAbility) {
					if (custAbility.getAbilityId().equals(abilityDto.getAbilityId())) {
						custAbilityVo.setIsDone(1);
						// 取当前完成的最大的特权
						if (null == maxAbilityDto || null == maxAbilityDto.getAbilityId()) {
							maxAbilityDto = abilityDto;
						} else if (maxAbilityDto.getAbilityId() < abilityDto.getAbilityId()) {
							maxAbilityDto = abilityDto;
						}
						break;
					}
				}
				custAbilityVos.add(custAbilityVo);
			}

			String mes = "您当前拥有" + maxAbilityDto.getAbilityName() + "权益;每次贷款、办卡成功均可享"
					+ AbilityEnum.getAmtByIndex(maxAbilityDto.getAbilityId()) / 100 + "元额外返现哦~";
			responseVo.setHomeTip(mes);// 最高的特权描述

			responseVo.setIdentityMedals(custAbilityVos);

			List<CustAbilityDimensionVo> custAbilityDimensionVos = new ArrayList<CustAbilityDimensionVo>();
			long totalScore = 0L;

			// 获取指数维度
			List<CreditDimensionDto> listDimension = custAbilityManager.findCustOwnDimension(cust);
			for (CreditDimensionDto creditDimensionDto : listDimension) {
				CustAbilityDimensionVo custAbilityDimensionVo = new CustAbilityDimensionVo();
				custAbilityDimensionVo.setName(creditDimensionDto.getDimensionName());
				custAbilityDimensionVo.setValue(creditDimensionDto.getDimensionScore() == 0 ? 0
						: creditDimensionDto.getDimensionScore() * 100 / creditDimensionDto.getDimensionTotal());

				custAbilityDimensionVos.add(custAbilityDimensionVo);
				totalScore += creditDimensionDto.getDimensionScore();
			}
			responseVo.setCreditIndex(Utility.spunYuan(totalScore));
			responseVo.setIndexDimensions(custAbilityDimensionVos);

			// 已通过认证的产品
			List<MerchantProductDto> merchantProductDtos = custProductManager.queryProductAuth(cust.getLastProccessId(),
					true, true);
			// 已申请的产品
			List<MerchantProductDto> applyProducts = custProductManager.queryApplyProduct(cust.getCustId());

			// 最大的信用值
			responseVo.setCreditValue(calcMaxCreditAmt(merchantProductDtos));

			// 去除已申请的产品
			AppUtil.excludeApplyProducts(merchantProductDtos, applyProducts);
			// 可以申请的产品数
			responseVo.setAllowApplyQty(merchantProductDtos.size());

			// 获取所有认证项目及其状态
			List<AuthItemDto> recommendAuthItemsAll = custAbilityManager.findRecommendAuthItem(cust);
			int doneQty = 0;
			int returnCount = 6;// 返回的数据个数

			// 返回数据List
			List<SimpleAuthItemVo> simpleAuthItemVos = new ArrayList<SimpleAuthItemVo>();
			for (AuthItemDto authItemDto : recommendAuthItemsAll) {

				if (authItemDto.getIsFinish() == 1) {// 已认证
					doneQty += 1;
				}
				// 添加需返回的数据
				if (returnCount > 0) {
					simpleAuthItemVos.add(new SimpleAuthItemVo(authItemDto.getName(), authItemDto.getDesc(),
							authItemDto.getIconUrl(), authItemDto.getIsFinish(), authItemDto.getFrontId()));
					returnCount = returnCount - 1;
				}
			}
			// 认证项总个数
			responseVo.setTotalQty(recommendAuthItemsAll.size());
			// 已完成认证项个数
			responseVo.setDoneQty(doneQty);
			// 填充返回数据
			responseVo.setAuthItems(simpleAuthItemVos);
			return responseVo;
		}catch (Exception ex){
			ex.printStackTrace();
			logger.error(ex.getStackTrace().toString());
			return null;
		}
	}
	
	@Log
	@RequestMapping("/newIndex")
	public NewIndexResonseVo newIndex(HttpServletRequest request) throws Exception {
		try {
			Cust cust = super.getCust(request);
			
			NewIndexResonseVo responseVo = new NewIndexResonseVo();
			
			OrderStatistics orderStatistics = new OrderStatistics();
			int loanCount = custProductManager.getSuccessLoanApplyCount(cust.getCustId());			
			int cardCount = custRecommendCardManager.getSuccessCardApplyCount(cust.getCustId());
			orderStatistics.setDoneLoanQty(loanCount);
			orderStatistics.setDoneCardQty(cardCount);
			responseVo.setOrderStatistics(orderStatistics);
			
			WalletInfo walletInfo = new WalletInfo();
		    BigDecimal accumulatedAmt = myIncomeManager.getAccumulatedIncome(cust.getCustId());
		    walletInfo.setAccumulatedAmt(accumulatedAmt);
		    BigDecimal balance = myWalletManager.getBalanceAmt(cust.getCustId());
		    walletInfo.setBalanceAmt(balance);
		    responseVo.setWalletInfo(walletInfo);
		    
			List<CardGrade> cardGradeList = new ArrayList<CardGrade>();			
			// 获取所有特权卡
			List<AbilityDto> allAbilities = custAbilityManager.findAllAbilities();
			// 获取拥有的特权卡
			List<CustAbility> listCustAbility = custAbilityManager.findCustAbilities(cust);

			for (AbilityDto abilityDto : allAbilities) {
				CardGrade cardGrade = new CardGrade();
				cardGrade.setCardType(abilityDto.getAbilityId().intValue());
				cardGrade.setCardName(abilityDto.getAbilityName());
				String conditionDesc="";
				int loanQty=0;
				
				for(AbilityEnum abilityEnum : AbilityEnum.values()) {
					if(abilityEnum.getCode() == abilityDto.getAbilityId()) {
						conditionDesc = abilityEnum.getConditionDesc();
						loanQty =  abilityEnum.getConditionCount();
					}
				}
			/*	if(abilityDto.getAbilityId()==AbilityEnum.Normal.getCode()){
					conditionDesc = AbilityLoanCardCountEnum.Normal.getDesc();
					loanQty =  AbilityLoanCardCountEnum.Normal.getCode();
				}else if(abilityDto.getAbilityId()==AbilityEnum.Silver.getCode()){
					conditionDesc = AbilityLoanCardCountEnum.Silver.getDesc();
					loanQty =  AbilityLoanCardCountEnum.Silver.getCode();
				}else if(abilityDto.getAbilityId()==AbilityEnum.Gold.getCode()){
					conditionDesc = AbilityLoanCardCountEnum.Gold.getDesc();
					loanQty =  AbilityLoanCardCountEnum.Gold.getCode();
				}else if(abilityDto.getAbilityId()==AbilityEnum.Platinum.getCode()){
					conditionDesc = AbilityLoanCardCountEnum.Platinum.getDesc();
					loanQty =  AbilityLoanCardCountEnum.Platinum.getCode();
				}else if(abilityDto.getAbilityId()==AbilityEnum.Diamond.getCode()){
					conditionDesc = AbilityLoanCardCountEnum.Diamond.getDesc();
					loanQty =  AbilityLoanCardCountEnum.Diamond.getCode();
				}else if(abilityDto.getAbilityId()==AbilityEnum.Black.getCode()){
					conditionDesc = AbilityLoanCardCountEnum.Black.getDesc();
					loanQty =  AbilityLoanCardCountEnum.Black.getCode();
				}*/
				cardGrade.setConditionDesc(conditionDesc);
				cardGrade.setLoanQty(loanQty);

				for (CustAbility custAbility : listCustAbility) {
					if (custAbility.getAbilityId().equals(abilityDto.getAbilityId())) {
						cardGrade.setGetStatus(1);						
						String cardNo = custAbility.getCustAbilityId().toString();
						while(cardNo.length()<16){
							cardNo ="0"+cardNo;
						}
						cardGrade.setCardNo(cardNo);
						break;
					}
				}
				
				List<CardValue> cardValue = new ArrayList<CardValue>();
				CardValue loanRepay = new CardValue();
				loanRepay.setPrivilegeId("1");
				loanRepay.setPrivilegeName("贷款返现");
				loanRepay.setValueDesc(abilityDto.getAbilityRights());
				cardValue.add(loanRepay);
				CardValue cardRepay = new CardValue();
				cardRepay.setPrivilegeId("2");
				cardRepay.setPrivilegeName("办信用卡返现");
				cardRepay.setValueDesc(abilityDto.getAbilityRights());
				cardValue.add(cardRepay);
				cardGrade.setCardValue(cardValue);
				
				cardGradeList.add(cardGrade);
			}
			responseVo.setCardGradeList(cardGradeList);
	
			return responseVo;
		}catch (Exception ex){
			ex.printStackTrace();
			logger.error(ex.getStackTrace().toString());
			return null;
		}
	}
	

	private Integer calcMaxCreditAmt(List<MerchantProductDto> merchantProductDtos) {
		if (0 == merchantProductDtos.size()) {
			return 0;
		} else {
			Integer max = 0;
			for (MerchantProductDto merchantProductDto : merchantProductDtos) {
				max = merchantProductDto.getProductMaxcredit().compareTo(max) > 0
						? merchantProductDto.getProductMaxcredit() : max;
			}
			return max;
		}
	}

	@RequestMapping("/custAbility")
	@Log
	public AbilityResponseVo getAbilityOwned(HttpServletRequest request) {
		Cust cust = super.getCust(request);

		// 获取所有特权
		List<AbilityDto> allAbilities = custAbilityManager.findAllAbilities();

		// 获取拥有的特权
		List<AbilityDto> listCustAbility = custAbilityManager.findCustOwnAbilities(cust);

		AbilityResponseVo responseVo = new AbilityResponseVo();
		List<CustAbilityVo> custAbilityVos = new ArrayList<CustAbilityVo>();

		for (AbilityDto abilityDto : allAbilities) {
			CustAbilityVo custAbilityVo = new CustAbilityVo();
			custAbilityVo.setValueDesc(abilityDto.getAbilityRights().toString());
			custAbilityVo.setPrivilegeId(abilityDto.getAbilityId().toString());
			for (AbilityDto custAbility : listCustAbility) {
				if (custAbility.getAbilityId().equals(abilityDto.getAbilityId())) {
					custAbilityVo.setIsDone(1);
				}
			}
			custAbilityVos.add(custAbilityVo);
		}

		responseVo.setIdentityMedals(custAbilityVos);
		return responseVo;
	}

	@RequestMapping("/taskItems")
	@Log
	public TaskItemResponeseVo getTaskItems(HttpServletRequest request) {
		Cust cust = super.getCust(request);
		TaskItemResponeseVo responseVo = new TaskItemResponeseVo();
		List<TaskItemVO> taskItems = new ArrayList<TaskItemVO>();

		int loanCount = custProductManager.getSuccessLoanApplyCount(cust.getCustId());
		TaskItemVO loanItem = new TaskItemVO();
		loanItem.setTaskId(TaskItemEnum.LoanCount.getCode());
		loanItem.setDoneQty(loanCount);
		taskItems.add(loanItem);
		int cardCount = custRecommendCardManager.getSuccessCardApplyCount(cust.getCustId());
		TaskItemVO cardItem = new TaskItemVO();
		cardItem.setTaskId(TaskItemEnum.CardCount.getCode());
		cardItem.setDoneQty(cardCount);
		taskItems.add(cardItem);
		responseVo.setTaskItems(taskItems);
		return responseVo;

	}

	@SuppressWarnings("rawtypes")
	@RequestMapping("/addAbility")
	@Log
	public JsonResult addAbility(@RequestBody @Valid AddAbilityParam param, HttpServletRequest request)
			throws Exception {
		Cust cust = super.getCust(request);
		custAbilityManager.addAbility(param.getPrivilegeId(), cust.getCustId());
		return JsonResult.SuccessResponse(null);
	}
}
